import { Group, LoadingManager } from 'three'
import { TDSLoader } from 'three/examples/jsm/Addons.js'
import type { DirBlobDataItem } from '../../resource-management/entities'

export class ThreeTDSLoader {
  public constructor() {}

  public async loadTDSModel(url: string): Promise<Group> {
    const manager = new LoadingManager()
    console.log('[loadTDSModel]:', url)

    // manager.setURLModifier 用于为loader的url请求设置一个代理
    // loader加载资源涉及的所有url都会经过这个代理人，包括loadAsync(url);的这个url
    // 注意，这个url(应该是.3ds .max)文件内部所需的相关资源url，在manager查找时会自动带上相对前缀（依据url路径提取出前缀）
    // 相对地址前缀 + 文件内部资源url = innerUrl
    manager.setURLModifier((innerUrl) => {
      console.log('>>>need url:', innerUrl)
      return innerUrl
    })

    const tdsLoader = new TDSLoader(manager)
    const group = await tdsLoader.loadAsync(url)

    return group
  }

  /** 加载模型，通过blob地址
   * @param path
   * @param dirBlobData
   * @returns
   */
  public async loadModel(path: string, dirBlobData?: DirBlobDataItem): Promise<Group> {
    const manager = new LoadingManager()

    if (dirBlobData) {
      const blobPath_blobUrlMap = dirBlobData.blobPathUrlMap
      // 设置tdsloader资源查找代理，去blobPath_blobUrlMap寻找资源
      manager.setURLModifier((innerUrl) => {
        // console.log('[o] need url:', innerUrl)
        if (blobPath_blobUrlMap.has(innerUrl)) {
          console.log('[√] modifier success:', innerUrl, blobPath_blobUrlMap.get(innerUrl))
          return blobPath_blobUrlMap.get(innerUrl) as string
        } else {
          console.warn('[x] modifier failed:', innerUrl)
          return innerUrl
        }
      })
    }

    const tdsLoader = new TDSLoader(manager)
    const group = await tdsLoader.loadAsync(path)

    return group
  }
}
